//
//  ProjectConfig.m
//  QinjinProject
//
//  Created by Michael on 14-9-12.
//  Copyright (c) 2014年 ___Michael___. All rights reserved.
//

#import "ProjectConfig.h"
#import "AFNetworkReachabilityManager.h"
#import "LoginViewController.h"


@interface ProjectConfig()
{
   // BOOL updateCityOrLocalData;
    NSMutableDictionary * version;//版本信息
  //  BOOL isAFNetworkReachability;
}
@end

@implementation ProjectConfig


-(id)init
{
    self = [super init];
    if (self)
    {
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        
        self.arrCity = [[NSMutableArray alloc]initWithCapacity:0];
        self.dicAcademicTitle = [[NSMutableDictionary alloc]initWithCapacity:0];
        self.dicClinicalTitle = [[NSMutableDictionary alloc]initWithCapacity:0];
        self.dicGender = [[NSMutableDictionary alloc]initWithCapacity:0];
        self.dicBookingTravelType = [[NSMutableDictionary alloc]initWithCapacity:0];
       // self.dicPaymentUrl = [[NSMutableDictionary alloc]initWithCapacity:0];//支付Url
        self.dicAllUrl = [[NSMutableDictionary alloc]initWithCapacity:0];
    }
    return self;
}

-(void)loadData
{
    [self loadLocalData];//初始化默认的数据防止在请求数据过程中操作相关的接口
    [self getAFNetworkReachabilityStatus];//根据网络情况请求数据
}

-(void)getAFNetworkReachabilityStatus
{
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
     {
        // [self setValue:[NSString stringWithFormat:@"%ld",(long)status] forKey:@"reachabilityStatus"];
         switch (status) {
             case AFNetworkReachabilityStatusReachableViaWWAN:
             {
                 //wlan网络
                 [self isUpdateData];//是否更新数据
             }
                 break;
             case AFNetworkReachabilityStatusReachableViaWiFi:
             {
                 //wifi网络
                 [self isUpdateData];//是否更新数据
             }
                 break;
             default:
             {
             }
                 break;
         }
     }];
}


//得到文件路径
-(NSString*)dataFilePath:(NSString*)fileName
{
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDiretory = [paths objectAtIndex:0];
    return [documentsDiretory stringByAppendingPathComponent:fileName];
}

#pragma mark 初始化获取本地信息
-(void)loadLocalData
{
    //版本号(如果没有版本号,保存默认的版本号)
    NSError * error;
    NSString * filePath = [self dataFilePath:dataversion_FILENAME];
    BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (!fileExist)
    {
        NSMutableDictionary * dicData = [NSMutableDictionary dictionaryWithCapacity:0];
        [dicData setObject:@"00000000" forKey:@"version"];
        [dicData setObject:@"http://api.mingyizhudao.com/apimd/localdata?" forKey:@"localdataUrl"];
        [self writeToFile:dataversion_FILENAME writeData:dicData];
    }
    
    //基本数据
    filePath = [self dataFilePath:LOCALDATA_FILENAME];
    fileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (fileExist)
    {
        NSMutableDictionary* userDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
         //DLog(@"==%@",userDic);
        if (userDic.allKeys.count>0)
        {
            [self.dicAcademicTitle addEntriesFromDictionary:[userDic objectForKey:@"academicTitle"]];
            [self.dicClinicalTitle addEntriesFromDictionary:[userDic objectForKey:@"clinicalTitle"]];
            [self.dicGender addEntriesFromDictionary:[userDic objectForKey:@"gender"]];
            [self.dicBookingTravelType addEntriesFromDictionary:[userDic objectForKey:@"bookingTravelType"]];
           // [self.dicPaymentUrl setObject:[dicResults objectForKey:@"paymentUrl"] forKey:@"paymentUrl"];
            [self.dicAllUrl addEntriesFromDictionary:[userDic objectForKey:@"url"]];
            [self.arrCity addObjectsFromArray:[userDic objectForKey:@"city"]];
        }
        
    }else
    {
        
        NSString *strPath = [[NSBundle mainBundle]pathForResource:@"localdataPaty"ofType:@"json"];
        NSData *jdata = [[NSData alloc]initWithContentsOfFile:strPath];
        id jsonObject = [NSJSONSerialization JSONObjectWithData:jdata options:NSJSONReadingMutableLeaves error:&error];
        if ([jsonObject isKindOfClass:[NSDictionary class]])
        {
            DLog(@"==%@",jsonObject);
            [self.dicAcademicTitle addEntriesFromDictionary:[jsonObject objectForKey:@"academicTitle"]];
            [self.dicClinicalTitle addEntriesFromDictionary:[jsonObject objectForKey:@"clinicalTitle"]];
            [self.dicGender addEntriesFromDictionary:[jsonObject objectForKey:@"gender"]];
            [self.dicBookingTravelType addEntriesFromDictionary:[jsonObject objectForKey:@"bookingTravelType"]];
            //[self.dicPaymentUrl setObject:[jsonObject objectForKey:@"paymentUrl"] forKey:@"paymentUrl"];
            [self.dicAllUrl addEntriesFromDictionary:[jsonObject objectForKey:@"url"]];
            [self.arrCity addObjectsFromArray:[jsonObject objectForKey:@"city"]];
            
            [self writeToFile:LOCALDATA_FILENAME writeData:jsonObject];
        }

    }

}


-(void)isUpdateData
{
    NSString * strUrl = @"/dataversion";
   
    [[HttpClient manager]GET:strUrl
                      parameters:nil
                         success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        if([[responseObject objectForKey:requestDataKey] isKindOfClass:[NSDictionary class]])
        {
           // DLog(@"=所有接口数据=%@",responseObject);
            
            version = [NSMutableDictionary dictionaryWithDictionary:[responseObject objectForKey:requestDataKey]];
            NSString * strNewResults = NullObjToString([version objectForKey:@"version"]);
            
            //old数据
            NSString * strOldResults = @"old";
            NSString * filePath = [self dataFilePath:dataversion_FILENAME];
            BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
            if (fileExist)
            {
              NSMutableDictionary * dicData = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
              strOldResults = [dicData objectForKey:@"version"];
            }
            if (![strOldResults isEqualToString:strNewResults])//需要请求
            {
              [self requestLocalData:[version objectForKey:@"localdataUrl"]];//
            }
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error)
    {
      //  DLog(@"=error:=%@",error.domain);
    }];
    
}

-(void)requestLocalData:(NSString *)strUrl
{
    strUrl = [NSString stringWithFormat:@"%@",strUrl];
    
    [[HttpClient manager]GET:strUrl
                  parameters:nil
    success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
        // DLog(@"==%@",responseObject);
        id data = [responseObject objectForKey:requestDataKey];
         
        if ([data isKindOfClass:[NSDictionary class]])
        {
            int updateData = 0;
            
            //================社会职称==============
            id dataParameters = [data objectForKey:@"academicTitle"];
            if ([dataParameters isKindOfClass:[NSDictionary class]])
            {
                if ([dataParameters allKeys].count >0)
                {
                    [self.dicAcademicTitle addEntriesFromDictionary:dataParameters];
                    updateData = 1;
                }
            }
            
            //===============医院职称===============
            dataParameters = [data objectForKey:@"clinicalTitle"];
            if ([dataParameters isKindOfClass:[NSDictionary class]])
            {
                if ([dataParameters allKeys].count >0)
                {
                   [self.dicClinicalTitle addEntriesFromDictionary:dataParameters];
                   updateData = 2;
                }
            }
            
            //=================性别================
            dataParameters = [data objectForKey:@"gender"];
            if ([dataParameters isKindOfClass:[NSDictionary class]])
            {
                if ([dataParameters allKeys].count >0)
                {
                  [self.dicGender addEntriesFromDictionary:dataParameters];
                   updateData = 3;
                }
            }
            
            //===============接诊方式===============
            dataParameters = [data objectForKey:@"bookingTravelType"];
            if ([dataParameters isKindOfClass:[NSDictionary class]])
            {
                if ([dataParameters allKeys].count >0)
                {
                  [self.dicBookingTravelType addEntriesFromDictionary:dataParameters];
                  updateData = 4;
                }
            }
            
            //=================城市==============
            dataParameters = [data objectForKey:@"city"];
            if ([dataParameters isKindOfClass:[NSArray class]])
            {
                NSArray * arr = [NSArray arrayWithArray:dataParameters];
                if (arr.count >0)
                {
                    [self.arrCity addObjectsFromArray:dataParameters];
                    updateData = 5;
                }
            }
            
            //==================url==============
            if ([data objectForKey:@"url"])
            {
                dataParameters = [data objectForKey:@"url"];
            }else
            {
               dataParameters = data;
            }
            if ([dataParameters isKindOfClass:[NSDictionary class]])
            {
                if ([dataParameters allKeys].count >0)
                {
                    [self.dicAllUrl addEntriesFromDictionary:dataParameters];
                    updateData = 6;
                }
            }

            if (updateData == 6)//
            {
              [self writeToFile:LOCALDATA_FILENAME writeData:data];
              [self writeToFile:dataversion_FILENAME writeData:version];
            }
        }
     } failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {}];
}


-(void)readFromUserDataFile
{
    self.dicUserData = [[NSMutableDictionary alloc]initWithCapacity:0];
   [self.dicUserData setObject:@"" forKey:USER_tel];
   [self.dicUserData setObject:@"" forKey:USER_token];
    
    NSString * filePath = [self dataFilePath:USERPROFILE_FILENAME];
    BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (fileExist)
    {
      NSMutableDictionary* userDic = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
      [self.dicUserData addEntriesFromDictionary:userDic];
    }
}


-(void)writeToFile:(NSString *)path writeData:(NSMutableDictionary *)data
{
    DLog(@"=writeToFilepath:=%@==data:=%@",path,data);
    NSString * filePath = [self dataFilePath:path];
    NSMutableDictionary* userDic = [NSMutableDictionary dictionaryWithDictionary:data];
    [userDic writeToFile:filePath atomically:YES];
}

#pragma mark 用户是否有效
-(BOOL)userIsEffective
{
    BOOL isProfile = [[self.dicUserData objectForKey:USER_isProfile] boolValue];
    if (isProfile)
    {
        return YES;
        
    }else
    {
        UIAlertView *alertNeedLogin = [[UIAlertView alloc] initWithTitle:alerTitle message:@"请到个人信息界面补全资料信息!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alertNeedLogin show];
    }
    return NO;
}

-(BOOL)isLogin
{
    
  if (![[self.dicUserData objectForKey:USER_token] isEqualToString:@""])
  {
     return YES;
  }
  return NO;
}


-(BOOL)needLogin
{
    //无token记录-未登陆
    if ((NullObjToString(self.dicUserData[USER_token])).length == 0)
    {
        UIAlertView *alertNeedLogin = [[UIAlertView alloc] initWithTitle:alerTitle message:@"请先登录!" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"登录",nil];
        [alertNeedLogin show];
        return YES;
    }
    return NO;
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex != alertView.cancelButtonIndex)
    {
        
        
        LoginViewController *lgVC = [[LoginViewController alloc]init];
        MyNavigationController *navi  = [[MyNavigationController alloc]initWithRootViewController:lgVC];
        UIViewController * showing = [[gApp.nav viewControllers] lastObject];
       // DLog(@"==%@",showing);
        [showing presentViewController:navi animated:YES completion:^{}];
    }
}

-(void)dealloc
{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

@end






